var VIPBusinessMail = Class.create();
VIPBusinessMail.prototype = {
    initialize : function(){
                     //this.init();
                     //类别
                     //0    商务问候
                     //1    日常问候
                     this.bsmtype = 0;
                     //发送频率
                     //0    每周
                     //1    每月
                     this.bsmfreq = 0;
                     //发送的具体日期
                     //月份【1-31】
                     //星期【1-7】
                     this.bsmday = 0;
                     //是否包含节日
                     this.isFes = 0;
                     this.preImgURLS = [ MailConst.ALL + '/0_1.jpg', MailConst.ALL + '/1_1.jpg' ];
                     //定制的节日
                     this.customDays = [];
                     this.customSubject = 0;
                 },

    checksetStatus : function(){
                         var uinfo = USERINFO.evalJSON();
                         if( uinfo.user_ext_status == 4 ){
                             //按照要求，冻结期的用户账户是要被删除掉滴
                             var param = {
                                 'mail_type' : 1
                             };
                             DeleteBusinessMail( param, businessmail.deleteSuccessS, businessmail.updateGlobalDataE );
                             return;
                         }
                         ListBusinessMail( { 'mail_type' : 1 }, this.updateGlobalData, this.updateGlobalDataE );
         },
    deleteSuccessS : function( ret ){
                        if( ret == 0 ) {
                           businessmail_set_flag = 2;
                        }
                        else{
                           businessmail_set_flag = 3;
                        }
                     },
    updateGlobalData : function( ret ){
                       if( ret != 0 && ret != 1 ){
                           businessmail_set_flag = 1;
                       }
                       else{
                           businessmail_set_flag = 2;
                       }
                    },
    updateGlobalDataE : function( ){
                           businessmail_set_flag = 3;
                        },

    init: function(){
				if(frozenAlert())
					return;
              //this.getInfoFromServer();
              ListBusinessMail( { 'mail_type' : 1 }, this.getInfoFromServerCallBack, this.getInfoFromServerFaild );
          },
    getInfoFromServerFaild: function(){
                            //先应该去服务器上取一下数据，我忽略这一步先
                           //this.getInfoFromServerCallBack();
                           businessmail_set_flag = 3;
                           alert( '获取信息失败，请稍后尝试' );
                   },
    getInfoFromServerCallBack : function( ret ){
                                    //返回0 <--可能是各种错误
                                    //返回1 <--用户信息不存在
		                            hiddenAllPanel();
		                            $("mailConfiguration").show();
                                    if( ret != 0 && ret != 1 ){
                                        businessmail.initWithData(ret);
                                    }
                                    else{
                                        businessmail.initEmptyPage();
									    $( 'bsmshow' ).src = businessmail.preImgURLS[ businessmail.bsmtype ];
                                    }									
                                },
    initEmptyPage : function(){
                        var dis = '';
                        for( var i = 1; i < 32; i++ ){
                            dis +="<option>" + i + "</option>";
                        }
                        var t = new Template(BussinessEmailTemplate);
                        var data = new Object();
                        data[ 'monthstr' ] = dis;
                        data[ 'addresses' ] = addressBookHTML();
                        $('mailConfiguration').update( t.evaluate(data) );
                        src_focus_id = 'business_mail_tos';
                    },
    selectType: function(){
                    this.bsmtype =  $( 'bsmtype' ).selectedIndex;
                    $( 'bsmshow' ).src = this.preImgURLS[ this.bsmtype ];
                },
    changeSign : function(){
                     var sign_type = $( 'signtype' ).selectedIndex;
                     if( sign_type == 1 ){
		                if (!mailCfgClass.getProfileContent().signatureCard|| mailCfgClass.getProfileContent().signatureCard.strip() == "{}") {
                             alert( "您的文字签名为空，请先设置签名" );
                             $( 'signtype' ).selectedIndex = 0;
                         }
                     }
                     if( sign_type == 2 ){
                        jsoplog.ucCapture('card');
		                if (!mailCfgClass.getProfileContent().signatureCard|| mailCfgClass.getProfileContent().signatureCard.strip() == "{}") {
                             alert( "您的名片签名为空，请先设置签名" );
                             $( 'signtype' ).selectedIndex = 0;
                         }
                     }
					return;
                 },
    changeSubject : function(){
                        var sdex = $( 'bsmsubject' ).selectedIndex;
                        this.customSubject = ( sdex == 2 ) ? 1 : 0;
                        if( this.customSubject == 1 ){
                            Element.setStyle( $( 'customSubject' ), { display : '' } );
                        }else{
                            Element.setStyle( $( 'customSubject' ), { display : 'None' } );
                        }
                    },
    changeFreq : function(){
                     var sdex = $( 'bsmfreq' ).selectedIndex;
                     if( sdex == 0 ){
                         Element.setStyle( $( 'monthselector' ), { display : 'None' } );
                         Element.setStyle( $( 'bsmday' ), { display : '' } );
                     }
                     else{
                         Element.setStyle( $( 'monthselector' ), { display : '' } );
                         Element.setStyle( $( 'bsmday' ), { display : 'None' } );
                     }
                  },
    cgetDate: function(){
                    var sdex = $( 'bsmfreq' ).selectedIndex;
                    var date_now = new Date();
                    if( sdex == 0 ){
                        //计算周
                        var index = $( 'bsmday' ).selectedIndex;
                        var weekindex_now = date_now.getDay();
                        var sub_index = 0 ;
                        sub_index = ( index == 0 ) ? ( 0 - weekindex_now ): index - weekindex_now - 1;
                        var res = custom_mail.dateAdd( date_now, "d", sub_index );
                        this.customDays = custom_mail.collectDays( res ).clone();
                    }else{
                        //计算月
                        var index = $( 'monthselector' ).selectedIndex + 1;
                        var monthindex_now = date_now.getDate();
                        var sub_index = index - monthindex_now;
                        var res = custom_mail.dateAdd( date_now, "d", sub_index );
                        this.customDays = custom_mail.collectMonths( res );
                    }
                },
    getFestival : function( ){
                  //长度判读
                  if( this.customDays.length == 0 )
                  {
                      // alert( "选择的日期有异常，请重新选择！" );
                      //_dialog.alert({info: '选择的日期有异常，请重新选择！'});
                      alert( '选择的日期有异常，请重新选择！' );
                      return false;
                  }
                  var start_datestr = this.customDays[ 0 ];
                  var end_datestr =  this.customDays[ this.customDays.length - 1 ];
                  var fesDays = custom_mail.collectSpecialDays( start_datestr, end_datestr ).uniq();
                  this.customDays.push( fesDays );
                  delete fesDays;
                  this.customDays = this.customDays.flatten().uniq();
              },
    submit: function(){
				if(frozenAlert(true)){
					return;
				}
                this.cgetDate();
                if( $( 'containFreq' ).checked ){
                    //包含节日
                    this.getFestival();
                }
                var params = {};

//{{{先是整理收信人
                var pattern = new RegExp("[^<^>\w]*@.[^<^>]*");
                var tids_html = $( 'business_mail_tos' ).value;
                tids_html = toTrimDBC(tids_html).replace(/;/ig, ',').replace(/；/ig, ',').replace(/，/ig, ',');
                tids_html = tids_html.replace( "\r", "" );
                tids_html = tids_html.replace( "\n", "" );
                var tids = tids_html.split( ',' );
                var emails = [];
                tids.each( function( q ){
                        if( q != null && q.strip() != "" ) {
                            if(q.indexOf('<') != -1 && q.indexOf('>') != -1) {
                                q = q.substring(q.indexOf('<')+1, q.indexOf('>'));
                            }
                        }
                        //防止只是组的时候出现的异常
                        //0 --  不是组
                        //1 --  是组
                        var gflag = 0;
                        //{{{ Step 所有联系人
                        if(q.strip() == '所有联系人') {
                        gflag = 1;
                        var glist = [];
                        contactLists.each(function(item) {
                            glist.push(item.email);
                            });
                        if(glist.length > 0) emails = emails.concat(glist);
                        }//}}}
                        //{{{Step 各个组
                        contactCates.each(function(item) {
                            if (item.name == q.strip()) {
                                gflag = 1;
                                var glist = [];
                                item.people.each(function(_item) {
                                    contactLists.each(function(__item) {
                                        if(_item == __item.name) glist.push(__item.email);
                                        });
                                });
                                if(glist.length > 0) emails = emails.concat(glist);
                             }
                         });
                        //}}}
                        if( gflag == 0 ){
                            if( q!="" && IsEmail( q ) ){
                            emails.push( q );
                            }
                        }
                });
                emails = emails.compact();
                if( emails.length < 1 ){
                    // alert( "最少要有一个收信人" );
                    //_dialog.alert({info: '最少要有一个收信人'});
                    alert( '最少要有一个收信人' );
                    return;
                }
				 if( emails.length > 18 ){
                    // alert( "最少要有一个收信人" );
                    //_dialog.alert({info: '最少要有一个收信人'});
                    alert( '最多只能有18个收信人' );
                    return;
                }
//}}}
//{{{ 收集各种信息
                //主题
                var _s = $('bsmsubject');
                params['subject'] = this.customSubject == 0 ? _s[_s.selectedIndex].innerHTML : $( 'customSubject' ).value;
                //用户ID
                params['uid'] = UserSohuID;
                //类别

                //是否签名
                //2 使用文字签名
                //1 使用名片签名
                //0 不用签名
                //if( $( 'signtype' ).selectedIndex>0 ){
                //    params[ 'isSign' ] = $( 'signtype' ).selectedIndex + 1
                //}else{
                //    params[ 'isSign' ] = 0;
                //}
				params[ 'isSign' ] = $( 'signtype' ).value;
                //params[ 'isSign' ] = $( 'isaddSign' ).checked == true ? 1 : 0;
                //签名类型
                //频率
                params[ 'freq' ] = $( 'bsmfreq' ).selectedIndex;
                //发送的日期
                params[ 'mailday' ] = Object.toJSON( this.customDays );
                //是否包含节日
                params[ 'isFre' ] = $( 'containFreq' ).checked == true ? 1 : 0;
                //是否抄送自己
                params[ 'cc_myself' ] = $( 'ccmyself' ).checked == true ? 1 : 0;
                //收件人
                params[ 'tid' ] = Object.toJSON( emails );
                //收费版本标志
                params[ 'mt' ] = 1;
                //类型
                params[ 'typeid' ] = $( 'bsmtype' ).selectedIndex;
                //地址本使用标记
                params[ 'addressbook_use_flag' ] = addressbook_use_flag;
//}}}           
                SendBusinessMail( params, this.SendMailCallBack, this.SendMailFail );
                addressbook_use_flag = 0;

            },
    SendMailCallBack : function( ret ){
                           if(ret == 0) {
                                  alert( "设置成功" );
                                  businessmail_set_flag = 1;
			                      hiddenAllPanel();
                                  $( 'mailConfiguration' ).style.display = '';
                                  businessmail.init();
                              } else {
                                  var msg = '';
                                  businessmail_set_flag = 2;
                                  switch( ret ) {
                                      case -1:msg = "设置的日期数量不合法";break;
                                      case -2:msg = "设置的收件人数量超过了18个";break;
                                      case -3:msg = "设置失败，请稍后重试";break;
                                      case -4:msg = "没有选择时间";break;
                                      default:msg = "未知错误";break;
                                  }
                                  alert( msg );
								  //_dialog.alert({info: msg});
                              }
                       },
    SendMailFail :function( ret ){
                      alert( '定制失败,请稍后再试' );
                  },
    deleteBSM : function( ){
                    if ( confirm( "删除此计划，未执行的计划邮件将不再被发送" ) == true ){
                        var param = {
                             'mail_type' : 1
       		            };
    		            DeleteBusinessMail(param, businessmail.deleteSuccess, businessmail.getInfoFromServerFaild);
                    }
                },
    deleteSuccess : function( ret ){
                        if( ret == 0 ) {
                            alert( "删除成功" );
                            businessmail_set_flag = 2;
                            //_dialog.alert({info: '删除成功'});
                            //changePanel("mainPage");
                            businessmail.init();
                        } else {
                             businessmail_set_flag = 3;
                             alert( "系统错误，请稍后重试！" );
                            //_dialog.alert({info: '系统错误，请稍后重试！'});
                        }
                    },

    initWithData: function( ret ){
                      var data = new Object();
                      var t = new Template(BussinessEmailListTemplate);
                      data[ 'bsmtype' ] = ret.typeid == 0 ? "日常问候" : "商务问候";
                      if( ret.isCC == 1 ){
                          data[ "str_ccself" ] = "抄送给自己";
                      } else {
                          data[ "str_ccself" ] = "无";
                      }
                      var fesdays = '';
                      var days = ret.mailday.split( "|" );
                      days = days.sort().compact();
                      var start = end = '';
                      var start_flag = 0;
                      days.each( function( d ) {
                              if( d != "" && start_flag == 0 )
                              {
                              start = d;
                              start_flag = 1;
                              }
                              }
                              );
                      end = days[ days.length -  1 ];
                      var freq_list = "";
                      if( ret.isFre == 1 && days.length > 0 )
                      {
//{{{寻找农历和公历（巩俐？？）的节日
                          days.each( function( d ){
                                  var nofestflag = 0;
                                  if( d != "" ){
                                  try{
                                  var ty = (""+ d).substr( 0, 4 );
                                  var tm = (""+ d).substr( 4, 2 );
                                  var td = (""+ d).substr( 6, 2 );
                                  tm = parseInt( tm );
                                  td = parseInt( td );
                                  ///{{{/先进行阳历（洋历？）的判断
                                  switch( tm ){
                                  case 1 : {
                                  if( td == 1 ){
                                  //元旦，古典节日中并没有这一天
                                  fesdays += "元旦节 ";
                                  }
                                  };break;
                                  case 10 : {
                                  if( td == 1 ){
                                  //国庆节，古典节日中也没有这样的一天
                                  fesdays += "国庆节 ";
                                  }
                                            };break;
                                  case 12 : {
                                                if( td == 25 ){
                                                    //圣诞节，唉，基督教的节日也要过的么？什么世道啊，我不信教。
                                                    fesdays += "圣诞节 ";
                                                }
                                            };break;
                                  };
                                  //}}}
                                  var flag = new Date( ty, tm-1, td );
                                  var q = new Lunar( flag );
                                  var res = custom_mail.isLurFesDays( q );
//{{{ switch
                                  switch( res ){
                                      case 6: {
                                                  if( freq_list.indexOf( "2" ) < 0 ){
                                                      fesdays +="端午节 ";
                                                      freq_list +="2";
                                                  }
                                              }break;
                                      case 7: {
                                                  if( freq_list.indexOf( "3" ) < 0 ){
                                                      fesdays +="中秋节 ";
                                                      freq_list +="3";
                                                  }
                                              }break;
                                      case 5: {
                                                  if( freq_list.indexOf( "1" ) < 0 ){
                                                      fesdays +="春节 ";
                                                      freq_list +="1";
                                                  }
                                              }break;
                                  };
                                  //}}}
                                  }catch( e ){
                                      //alert( e );
                                  }
                                  }
                          }
                          );//}}}
                      }
//{{{ 频率
                      if( fesdays == "" ){
                                fesdays = "无";
                      }
                      var str_freq = '';
                      if( ret.freq == 0){
                          str_freq = "每星期一次（共" + (days.length - 1 ) +" 封邮件）";
                      }
                      else if( ret.freq == 1 ){
                          str_freq = "每月一次（共" + (days.length - 1) +" 封邮件）";
                      }
//}}}
//{{{ 收信人
                     //收信人
                      var str_receivers = ret.tid;
                      tids = ret.tid.split( "," );
                      var flag_receiver = 0;
                      if( tids.length > 5 ){
                          for( var i = 0; i < tids.length; i++ ){
                              if( flag_receiver == 5 && tids[ i ] != ""){
                                  str_receivers += "</dd><dd>";
                                  str_receivers += tids[ i ] + ",";
                                  flag_receiver = 0;
                              }
                              else{
                                  if( tids[ i ] != "" ){
                                   str_receivers += tids[ i ] + ",";
                                   flag_receiver++;
                                  }
                              }
                          }
                      }
//}}}
//{{{ 表现字符串
                        var str_sign = "不使用签名";
                        var extra_subject = "";
                        try{
                            var o = PROFILE.signatureCard.evalJSON();
                            extra_subject = o.username;
                        }
                        catch( e ){}
                        if( ret.signtype == 2 ){
                            str_sign =  "名片签名";
                        }
                        else if ( ret.signtype == 1 ){
                            str_sign = "文字签名";
                        }
                        else{
                            str_sign = "不使用签名";
                        }
                      var retstr = "<dd>发送频率：" + str_freq + "</dd>"
                        + "<dd>包含节日：" + fesdays + "</dd>"
                        + "<dd>收 件 人：" + str_receivers + "</dd>"
                        + "<dd>邮件主题：" + extra_subject + " " + ret.subject + "</dd>";
                        if( ret.isCC == 1 ){
                            retstr += "<dd>抄    送：自己</dd>";
                        }
                        retstr += "<dd>签       名：" + str_sign + "</dd>";
//}}}
                        data[ "bsminfo" ] = retstr;
                        $('mailConfiguration').update( t.evaluate(data) );

                  },
                 // 当添加完联系人后，直接在地址簿那里追加一下联系人
    addContactCallBack : function(){
                             var ahtml = addressBookHTML();
                             //bsmaddress
                             var adnode = document.getElementsByClassName( 'bsmaddress' )[ 0 ];
                             adnode.removeChild( adnode.lastChild );
                             new Insertion.Bottom( adnode, ahtml );
                         }

};
var businessmail = new VIPBusinessMail();